package com.yupi.yupicturebackend.manager.upload;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;


@Slf4j
@Component
public abstract class PictureUploadTemplate {


    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     * @param intputSource
     * @param uploadPathPrefix
     * @return
     */
    public  UploadPictureResult uploadPicture(Object intputSource,String uploadPathPrefix) {

        //校验图片
        validPicture(intputSource);
        //图片上传地址
        String UUID = RandomUtil.randomString(16);
        String originalFilename = getOriginalFilename(intputSource);

        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
                UUID, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFilename);


        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(uploadPath, null);
            processFile(intputSource,file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //获取到图片处理结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                //获取压缩之后得到的文件信息
                CIObject compressCiObject = objectList.get(0);
                //默认缩略图等于压缩图
                CIObject thumbnailCiObject = compressCiObject;
                //有缩略图 才进行处理
                if(objectList.size()>1){
                    thumbnailCiObject = objectList.get(1);
                }

                //封装压缩图的返回结果
                return buildResult(originalFilename, compressCiObject,thumbnailCiObject,imageInfo);
            }

            return buildResult(imageInfo, uploadPath, originalFilename, file);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            this.deleteTempfile(file);
        }


    }



    /**
     * 封装返回结果
     * @param imageInfo
     * @param uploadPath
     * @param originalFilename
     * @param file
     * @return
     */



    /**
     * 校验输入流（本地 或者 Url）
     * @param intputSource
     */
    protected abstract void validPicture(Object intputSource);

    /**
     * 获取输入流的原始文件名
     * @param intputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object intputSource);

    /**
     * 处理输入流并处理本地临时文件
     * @param intputSource
     */
    protected abstract void processFile(Object intputSource,File file)throws Exception;


    /**
     * 封装返回结果
     * @param originalFilename  原始文件名
     * @param compressCiObject  压缩后的对象
     * @return imageInfo 图片信息
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressCiObject,CIObject thumbnailCiObject
    ,ImageInfo imageInfo) {
        int width = compressCiObject.getWidth();
        int height = compressCiObject.getHeight();
        double picScale = NumberUtil.round(width*1.0 / height,2).doubleValue();

        //封装返回对象
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        //设置压缩后原图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressCiObject.getFormat());
        uploadPictureResult.setPicFormat(imageInfo.getAve());
        //设置缩略图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());

        // 返回可访问地址
        return uploadPictureResult;
    }


    /**
     * 封装返回结果
     * @param imageInfo
     * @param uploadPath
     * @param originalFilename
     * @param file
     * @return
     */
    private UploadPictureResult buildResult(ImageInfo imageInfo, String uploadPath, String originalFilename, File file) {
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        double picScale = NumberUtil.round(width*1.0 / height,2).doubleValue();

        //封装返回对象
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicFormat(imageInfo.getAve());

        // 返回可访问地址
        return uploadPictureResult;
    }
    /**
     * 删除临时文件
     * @param file
     */
    public static void deleteTempfile(File file) {
        if (file != null) {
            // 删除临时文件
            boolean deleteResult = file.delete();
            if (!deleteResult) {
                log.error("file delete error, filepath = {}", file);
            }
        }
    }
}
